<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @close="btnCancel">
    <el-checkbox-group v-model="roleIds">
      <!-- 要显示角色名称 存储角色id   则label表示要存储的值 -->
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="btnOK">确 定</el-button>
        <el-button size="small" @click="btnCancel">取 消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'

export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: [], // 角色数据
      roleIds: [] // 当前用户的角色
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() { //  获取所有角色
      const { rows } = await getRoleList({ page: 1, pagesize: 20 }) // 默认10条数据
      this.list = rows
    },
    async getUserDetailById(id) { // 获取当前用户的角色
      const { roleIds } = await getUserDetailById(id) // props传值是异步的 这里不能用this.userId
      this.roleIds = roleIds // 赋值本用户的角色
    },
    async btnOK() { // 给用户分配角色
      await assignRoles({ id: this.userId, roleIds: this.roleIds })
      this.$message.success('设置成功')
      this.$emit('update:showRoleDialog', false)
      // this.$parent.showRoleDialog = false
    },
    btnCancel() {
      this.roleIds = [] // 清空原来的数组
      this.$emit('update:showRoleDialog', false)
    }

  }

}
</script>

<style>

</style>
